//
//  SigninForCaptchaViewController.m
//  Btpin
//
//  Created by Vic on 2019/4/4.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "SigninForCaptchaViewController.h"
#import "UILabel+YBAttributeTextTapAction.h"
#import "SigninAccountViewController.h"
#import "IDSelectViewController.h"
#import "AppDelegate.h"
#import "PersonalTabBarController.h"
#import "CompanyTabBarController.h"
//#import "ResignAgreementViewController.h"
#import "CompanyFirstInfoViewController.h"
#import "PMineResumeViewController.h"
#import "PersonalWorkExperienceViewController.h"
#import "CompanySecondInfoViewController.h"
#import "PersonalFirstInfoViewController.h"
#import "PersonalEducationInfoViewController.h"
#import "GeneralWebViewViewController.h"
#import "CompanyInfoViewController.h"
#import "ShareItemButton.h"
#import "RegisterViewController.h"
#import "WXBindingViewController.h"
#import "WXAuth.h"
#import "CountryCodeViewController.h"

@interface SigninForCaptchaViewController ()<UITextFieldDelegate>
{
//    UIButton *countryCodeBtn;
    UITextField *phoneTextField;
    UITextField *captchaTextField;
    
    UIButton *captchaButton;
    NSInteger timerInt;
    
    NSString *countryCodeStr;
}
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation SigninForCaptchaViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [DataToolsControl sharedManager].openSigninType = OpenSigninTypeOfWXSigninForCaptcha;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationWXCode:) name:NotificationForWXCode object:nil];
    timerInt = CaptchaTime;
//    countryCodeStr = @"86";
    countryCodeStr = @"";
    [self initUI];
    
    [DataToolsControl sharedManager].appJustOpen = NO;
}
- (void)notificationWXCode:(NSNotification *)notification {
    if ([DataToolsControl sharedManager].openSigninType != OpenSigninTypeOfWXSigninForCaptcha) {
        return;
    }
    NSString *code = [NSString stringWithFormat:@"%@", notification.userInfo[@"code"]];
    NSLog(@"%@", code);
    
    if (![code isEqualToString:UD_GetOForK(isOpenWXSigninCode)]) {
        return;
    }
    if ([DataToolsControl sharedManager].codeRecord != 1) {
        return;
    }
    [DataToolsControl sharedManager].codeRecord++;
    
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    if([DataToolsControl sharedManager].isApple){
        [dic setObject:@"apple" forKey:@"type"];
    }else{
        [dic setObject:@"weixin" forKey:@"type"];
    }

    [dic setObject:code forKey:@"code"];
    [dic setObject:@"" forKey:@"token"];
    
    [BaseNetManager requestWithMethod:POST path:User_OpenSignin_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDDismiss;
            id data = responseObject[@"data"];
            if ([data isKindOfClass:[NSDictionary class]] && ([data count]>0)) {
                [self detailDataAndPushVC:responseObject];
                
                [DataToolsControl autoLogin];
            } else {
                WXBindingViewController *WXBVC = [[WXBindingViewController alloc] init];
                [self.navigationController pushViewController:WXBVC animated:YES];
            }
        } else {
            NSString *str = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
            SVPHUDError(str);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)countryCodeBtnTap {
    CountryCodeViewController *CCVC = [[CountryCodeViewController alloc] init];
    CCVC.selectCode = ^(NSString * _Nonnull code) {
        self->countryCodeStr = code;
//        [self->countryCodeBtn setTitle:[NSString stringWithFormat:@"+ %@", code] forState:UIControlStateNormal];
    };
    [self.navigationController pushViewController:CCVC animated:YES];
}
- (void)initUI {
    self.navigationItem.title = @"验证码登录";
    
//    countryCodeBtn = [UIToolsControl initButtonWithFrame:CGRectMake(ScalePS(20), ScalePS(25), ScalePS(50), ScalePS(50)) imageName:nil target:self action:@selector(countryCodeBtnTap) title:[NSString stringWithFormat:@"+ %@", countryCodeStr] titleColor:THEMECOLOR_OF_TEXT_333333];
//    countryCodeBtn.titleLabel.font = Font(Font_15);
//    countryCodeBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
//    countryCodeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//    [self.view addSubview:countryCodeBtn];
//
    
//    phoneTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(EndX(countryCodeBtn)+10*Scale, 25*Scale, WIDTH-60*Scale-ScalePS(50), 50*Scale) placeholder:PhoneNumberPlaceholderText secureTextEntry:NO font:Font_17 padding:YES];
    phoneTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(30*Scale, 25*Scale, WIDTH-60*Scale, 50*Scale) placeholder:PhoneNumberPlaceholderText secureTextEntry:NO font:Font_17 padding:YES];
    [phoneTextField borderColor:THEMECOLOR_OF_TEXT_cccccc borderWidth:lineH borderType:BorderSideTypeBottom];
    phoneTextField.delegate = self;
    phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:phoneTextField];
    
    captchaTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(30*Scale, EndY(phoneTextField)+25*Scale, WIDTH-150*Scale, 50*Scale) placeholder:CaptchaPlaceholderText secureTextEntry:NO font:Font_17 padding:YES];
    captchaTextField.delegate = self;
    captchaTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:captchaTextField];
    UIView *lineView = [UIToolsControl initViewWithFrame:CGRectMake(30*Scale, EndY(captchaTextField)-1, WIDTH-60*Scale, lineH) backgroundColor:THEMECOLOR_OF_TEXT_cccccc];
    [self.view addSubview:lineView];
    captchaButton = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH-120*Scale, EndY(phoneTextField)+30*Scale, 100*Scale, 40*Scale) imageName:nil target:self action:@selector(sendCaptchaBtnTap) title:@"发送验证码" titleColor:THEMECOLOR_OF_TEXT_333333];
    captchaButton.titleLabel.font = Font(Font_14);
    [self.view addSubview:captchaButton];
    
    UIButton *okBtn = [UIToolsControl initButtonWithFrame:CGRectMake(40*Scale, EndY(captchaTextField)+70*Scale, WIDTH-80*Scale, 46*Scale) imageName:nil target:self action:@selector(okBtnTap) title:@"进入比特聘" titleColor:COLOR_OF_WHITE];
    okBtn.titleLabel.font = FontBold(Font_17);
    okBtn.backgroundColor = THEMECOLOR_OF_ORANGE;
    okBtn.layer.cornerRadius = 23*Scale;
    okBtn.layer.masksToBounds = YES;
    [self.view addSubview:okBtn];
    
    UIButton *accountBtn = [UIToolsControl initButtonWithFrame:CGRectMake(StartX(okBtn), EndY(okBtn)+10*Scale, 120*Scale, 40*Scale) imageName:nil target:self action:@selector(accountBtnTap) title:@"账号密码登录" titleColor:THEMECOLOR_OF_TEXT_333333];
    accountBtn.titleLabel.font = Font(Font_14);
    [self.view addSubview:accountBtn];
    
    //    @"手机验证码注册/登录"
    UIButton *registerBtn = [UIToolsControl initButtonWithFrame:CGRectMake(EndX(okBtn)-60*Scale, StartY(accountBtn), 60*Scale, 40*Scale) imageName:nil target:self action:@selector(registerBtnTap) title:@"注册" titleColor:THEMECOLOR_OF_ORANGE];
    registerBtn.titleLabel.font = Font(Font_14);
//    registerBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.view addSubview:registerBtn];
    
    NSString *clauseString = @"登录即代表您已同意我们的《服务协议》和《隐私政策》";
    CGFloat clauseStrWidth = [UIToolsControl textWidth:clauseString size:CGSizeMake(MAXFLOAT, 40*Scale) font:Font_13]+1;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:clauseString];
    [attributedString addAttribute:NSFontAttributeName value:Font(Font_13) range:NSMakeRange(0, clauseString.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:THEMECOLOR_OF_TEXT_666666 range:NSMakeRange(0, clauseString.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:THEMECOLOR_OF_ORANGE range:NSMakeRange(12, 13)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:THEMECOLOR_OF_TEXT_666666 range:NSMakeRange(18, 1)];
    UILabel *clauseLabel = [[UILabel alloc] initWithFrame:CGRectMake((WIDTH-clauseStrWidth)*0.5, HEIGHT-HeightOfStatusBarAndNavigationBar-SIMEmojKeyBoardkBottomNOSafeArea_Height-60*Scale, clauseStrWidth, 40*Scale)];
    clauseLabel.font = Font(Font_13);
    clauseLabel.backgroundColor = COLOR_OF_CLEAR;
    clauseLabel.attributedText = attributedString;
    clauseLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:clauseLabel];
    [clauseLabel yb_addAttributeTapActionWithStrings:@[@"《服务协议》", @"《隐私政策》"] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
        GeneralWebViewViewController *GWVC = [[GeneralWebViewViewController alloc] init];
        if ([string isEqualToString:@"《服务协议》"]) {
            NSLog(@"服务协议");
            GWVC.showType = GeneralWebViewTypeOfResignAgreement;
        } else {
            NSLog(@"隐私政策");
            GWVC.showType = GeneralWebViewTypeOfPrivacyPolicy;
        }
        GWVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:GWVC animated:YES];
    }];
    
    CGFloat itemWidth = (WIDTH-20*Scale)*0.25;
    ShareItemButton *wxSigninBtn = [[ShareItemButton alloc] initWithFrame:CGRectMake((WIDTH-itemWidth)*0.5, EndY(accountBtn)+170*Scale, itemWidth, 120*Scale) imageName:@"share_weixin_haoyou" itemText:@"微信登录"];
    [wxSigninBtn addTarget:self action:@selector(wxSigninBtnTap) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:wxSigninBtn];
    wxSigninBtn.hidden = ![UIToolsControl canOpenWXApp];
}
- (void)wxSigninBtnTap {
    if ([UIToolsControl canOpenWXApp]) {
        [WXAUTH sendWXAuthReq];
    } else {
        SVPHUDError(@"您还没有安装微信，请先安装微信");
    }
}
- (void)okBtnTap {
    [UIToolsControl resignFirstResponderForTextFieldArray:@[phoneTextField, captchaTextField]];
    if (phoneTextField.text.length>0) {
        if ([UIToolsControl validatePhoneNumber:phoneTextField.text]) {
            if (captchaTextField.text.length>0) {
                if ([UIToolsControl validateNumber:captchaTextField.text]) {
                    [self upDate];
                } else {
                    SVPHUDError(CaptchaOKAlertText);
                    [captchaTextField becomeFirstResponder];
                }
            } else {
                SVPHUDError(CaptchaAlertText);
                [captchaTextField becomeFirstResponder];
            }
        } else {
            SVPHUDError(PhoneNumberOKAlertText);
            [phoneTextField becomeFirstResponder];
        }
    } else {
        SVPHUDError(PhoneNumberAlertText);
        [phoneTextField becomeFirstResponder];
    }
}
- (void)upDate {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:phoneTextField.text forKey:@"mobile"];
    [dic setObject:captchaTextField.text forKey:@"verify_code"];
    [dic setObject:countryCodeStr forKey:@"country_code"];
    
    [BaseNetManager requestWithMethod:POST path:Signin_SMSSignin_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDSuccess(responseObject[@"msg"]);
            
            [self detailDataAndPushVC:responseObject];
        } else {
            NSString *str = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
            SVPHUDError(str);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)detailDataAndPushVC:(NSDictionary *)responseObject {
    [DataToolsControl dataAnalysisUserInfo:responseObject];
    UD_SetOForK(isYes, isSignin);
    UDSynchronize;
    
//      [DataToolsControl autoLoginForInitIM];
    [DataToolsControl initIMPeizhi];
    [AppDelegate loadLocationData];
    
    NSDictionary *data = responseObject[@"data"];
    if (data[@"user_guide"] && [data[@"user_guide"] length] && ([data[@"user_guide"] isEqualToString:@"choose_role"])) { // 用户还没选角色 （选择用户角色）
        IDSelectViewController *IDSVC = [[IDSelectViewController alloc] init];
        IDSVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:IDSVC animated:NO];
    } else {
        if ([data[@"user_guide"] isEqualToString:@"company_add_job"]) { // 添加工作
            [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                [SharedApp showViewController:TabBarTypeOfCompany];
                UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                tabBarController.selectedIndex = 1;
            }];
        } else if ([data[@"user_guide"] isEqualToString:@"company_create"]) { // 招聘者下面没有企业的话就会引导创建
            CompanyFirstInfoViewController *IDSVC = [[CompanyFirstInfoViewController alloc] init];
            IDSVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:IDSVC animated:NO];
        } else if ([data[@"user_guide"] isEqualToString:@"company_info"]) { // 填写企业信息
            CompanySecondInfoViewController *IDSVC = [[CompanySecondInfoViewController alloc] init];
            IDSVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:IDSVC animated:NO];
        } else if ([data[@"user_guide"] isEqualToString:@"company_audit"]) { // 企业未认证
            SVPHUDShow;
            [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                SVPHUDDismiss;
                [SharedApp showViewController:TabBarTypeOfCompany];
                UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                tabBarController.selectedIndex = tabBarController.viewControllers.count-1;
                RootNavigationController *navigationController = (RootNavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                
                CompanyInfoViewController *CIVC = [[CompanyInfoViewController alloc] init];
                CIVC.hidesBottomBarWhenPushed = YES;
                [navigationController pushViewController:CIVC animated:YES];
            }];
        } else if (([data[@"user_guide"] isEqualToString:@"resume_create"])) { // 创建简历页
            PersonalFirstInfoViewController *PMRVC = [[PersonalFirstInfoViewController alloc] init];
            PMRVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMRVC animated:NO];
        } else if ([data[@"user_guide"] isEqualToString:@"resume_edu"]) { // 完善简历中教育经历
            if (data[@"is_graduate"] && ([data[@"is_graduate"] integerValue] == 0)) {
                [DataToolsControl sharedManager].idType = IDTypeOfWorker;
            } else {
                [DataToolsControl sharedManager].idType = IDTypeOfFreshGraduate;
            }
            
            PersonalEducationInfoViewController *PMRVC = [[PersonalEducationInfoViewController alloc] init];
            PMRVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMRVC animated:NO];
        } else if ([data[@"user_guide"] isEqualToString:@"resume_work"]) { // 完善简历中工作经历
            PersonalWorkExperienceViewController *PMRVC = [[PersonalWorkExperienceViewController alloc] init];
            PMRVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMRVC animated:NO];
        } else {
            if ([data[@"user_role"] integerValue] == 1) {
                [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                    [SharedApp showViewController:TabBarTypeOfCompany];
                }];
            } else {
                [DataToolsControl getMyBaseInfoForWorker:^(BOOL requestFlag) {
                    [SharedApp showViewController:TabBarTypeOfPersonal];
                }];
            }
        }
    }
}
- (void)accountBtnTap {
    NSLog(@"accountBtnTap");
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)sendCaptchaBtnTap {
    NSLog(@"sendCaptchaBtnTap");
    if (phoneTextField.text.length>0) {
        if ([UIToolsControl validatePhoneNumber:phoneTextField.text]) {
            SVPHUDShow;
            __weak __typeof(self)weakSelf = self;
            [UIToolsControl getCaptcha:phoneTextField.text countryCode:countryCodeStr type:[UIToolsControl getCaptchaType:GetCaptchaTypeOfSignin] successBlock:^(id response) {
                __strong __typeof(weakSelf)strongSelf = weakSelf;
                if ([response[@"code"] integerValue] == 2000) {
                    SVPHUDSuccess(response[@"msg"]);
                    [self->captchaTextField becomeFirstResponder];
                    strongSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerClick) userInfo:nil repeats:YES];
                } else {
                    SVPHUDError(response[@"msg"]);
                }
            }];
        } else {
            SVPHUDError(PhoneNumberOKAlertText);
        }
    } else {
        SVPHUDError(PhoneNumberAlertText);
        [phoneTextField becomeFirstResponder];
    }
}
- (void)timerClick {
    timerInt--;
    if (timerInt>0) {
        [captchaButton setTitleColor:THEMECOLOR_OF_TEXT_cccccc forState:UIControlStateNormal];
        [captchaButton setTitle:[NSString stringWithFormat:@"%ldS", (long)timerInt] forState:UIControlStateNormal];
        captchaButton.userInteractionEnabled = NO;
    } else {
        [captchaButton setTitle:GetCaptchaText forState:UIControlStateNormal];
        [captchaButton setTitleColor:THEMECOLOR_OF_TEXT_333333 forState:UIControlStateNormal];
        captchaButton.userInteractionEnabled = YES;
        timerInt = CaptchaTime;
        [self.timer invalidate];
        self.timer = nil;
    }
}
- (void)customBackButtonTap {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)registerBtnTap {
    NSLog(@"registerBtnTap");
    RegisterViewController *RVC = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:RVC animated:YES];
}

@end
